<template>
	<!-- 加载页面 -->
	<div class="loading-screen" v-if="isLoading">
		<div class="cyber-grid"></div>
		<div class="cyber-lines"></div>
		<div class="loading-container">
			<div class="loading-logo">无伤的博客</div>
			<div class="loading-terminal">
				<div class="terminal-header">
					<div class="terminal-button"></div>
					<div class="terminal-button"></div>
					<div class="terminal-button"></div>
					<div class="terminal-title">system_init.exe</div>
				</div>
				<div class="terminal-body">
					<div class="terminal-line">Initializing system...</div>
					<div class="terminal-line">Loading components...</div>
					<div class="terminal-line">
						<span class="prompt">$></span> 
						<span class="command">load_resources</span>
					</div>
					<div class="terminal-line progress-line">
						<span class="progress-text">[</span>
						<div class="progress-container">
							<span class="progress-bar">{{ progressBar }}</span>
						</div>
						<span class="progress-text">]</span>
						<span class="progress-percentage">{{ loadingProgress }}%</span>
					</div>
					<div class="terminal-line" v-if="loadingProgress >= 100">
						<span class="success-text">System loaded successfully.</span>
					</div>
				</div>
			</div>
		</div>
		<div class="cyber-particles"></div>
	</div>

	<div class="Index-header" :class="{ 'fixed-header': isScrolled }">
		<Header />
	</div>
	<div class="Index-body">
		<div class="Index-ppt" ref="ppt" :class="{ 'Index-show': isShow }">
			<Ware class="Ware" />
			<PrintTxt style="margin-top: 150px;" />
		</div>
		<div class="Index-main">
			<Main />
		</div>
	</div>
	<div class="notice" v-show="isshownotice">
		<h1>公告</h1>
		<div class="notice-box">
			<div class="notice-txt" v-for="item in notice">
				{{item.txt}}
			</div>
		</div>

		<button @click="changeisshow()">关闭</button>
	</div>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onUnmounted,
		reactive,
		computed
	} from 'vue'; // 引入必要的 Composition API 函数
	import axios from 'axios';

	import Header from '../header/Header.vue'; // 引入你的 Header 组件
	import Ware from '../util/Wave.vue';
	import PrintTxt from '../util/PrintTxt.vue';
	import Main from './Main.vue';
	import bg1 from '@/img/indexbg/1.png';
	import bg2 from '@/img/indexbg/2.png';
	import bg3 from '@/img/indexbg/3.png';

	// 加载进度条状态
	const isLoading = ref(false); // 默认改为 false
	const loadingProgress = ref(0);
	let progressInterval = null;
	
	// 命令行进度条长度配置
	const maxEqualSigns = 73; // 100%时的等号数量
	
	// 控制光标闪烁
	const showCursor = ref(true);
	let cursorInterval = null;
	
	// 模拟命令行光标闪烁
	const blinkCursor = () => {
		cursorInterval = setInterval(() => {
			showCursor.value = !showCursor.value;
		}, 500);
	};
	
	// 命令行进度条显示
	const progressBar = computed(() => {
		// 计算当前进度对应的等号数量
		const equalCount = Math.floor(loadingProgress.value / 100 * maxEqualSigns);
		
		// 生成进度条字符串 - 等号 + > 箭头
		return '='.repeat(equalCount) + (showCursor.value ? '>' : ' ');
	});

	// 模拟加载进度
	const simulateLoading = () => {
		blinkCursor(); // 启动光标闪烁
		
		progressInterval = setInterval(() => {
			if (loadingProgress.value < 90) {
				// 随机增加进度，但最多增加到90%，留下最后10%给实际资源加载完成时
				loadingProgress.value += Math.floor(Math.random() * 3) + 1;
				if (loadingProgress.value > 90) {
					loadingProgress.value = 90;
				}
			}
		}, 200);
	};

	// 完成加载
	const completeLoading = () => {
		clearInterval(progressInterval);
		loadingProgress.value = 100;
		
		// 进度到100%后等待一小段时间再隐藏加载页面，给用户一个完成的视觉感知
		setTimeout(() => {
			isLoading.value = false;
			if (cursorInterval) {
				clearInterval(cursorInterval);
			}
		}, 1000);
	};

	//幻灯片
	const backgroundurl = reactive([
		bg1,
		bg2,
		bg3,
	]);
	const currentIndex = ref(0);
	const ppt = ref(null);
	const isShow = ref(false);
	const intervalId = ref(null); // To store the setInterval ID
	const showClassTimeoutId = ref(null); // To store the setTimeout ID

	const changeBackground = () => {
		if (!ppt.value) return; // Guard clause if element isn't ready

		// 1. Remove the .Index-show class immediately when starting a change cycle
		isShow.value = false;

		// 2. Clear any *pending* timeout for adding the class from the *previous* cycle
		if (showClassTimeoutId.value) {
			clearTimeout(showClassTimeoutId.value);
			showClassTimeoutId.value = null;
		}

		// 3. Set the new background image based on the *current* index
		const imageUrl = backgroundurl[currentIndex.value];
		ppt.value.style.backgroundImage = `url('${imageUrl}')`;

		// 4. Schedule adding the .Index-show class after 3 seconds
		showClassTimeoutId.value = setTimeout(() => {
			isShow.value = true;
			showClassTimeoutId.value = null; // Clear the stored ID after the timeout runs
		}, 3000); // 3000ms = 3 seconds

		// 5. Update the index for the *next* interval tick
		currentIndex.value = (currentIndex.value + 1) % backgroundurl.length; // Cycle through 0, 1, 2
	};

	// --- 状态定义 ---

	// 定义一个响应式变量 isScrolled，用于追踪头部是否应该被隐藏
	// true: 隐藏 (向下滚动), false: 显示 (向上滚动或在顶部)
	const isScrolled = ref(false);

	// 定义一个响应式变量 lastScrollTop，用于存储上一次滚动事件触发时的滚动条位置
	// 以便比较当前滚动位置来判断滚动方向
	const lastScrollTop = ref(0);

	// --- 事件处理函数 ---

	// 定义处理滚动事件的函数
	const handleScroll = () => {
		// 获取当前窗口的垂直滚动距离 (兼容多种浏览器)
		const currentScrollTop = window.pageYOffset || document.documentElement.scrollTop;
		const headerHeight = 50; // 你的头部实际高度，用于判断是否滚过了头部

		// 判断滚动方向
		if (currentScrollTop > lastScrollTop.value && currentScrollTop > headerHeight) {
			// --- 向下滚动 ---
			// 当前滚动位置 > 上次位置，表示向下滚动
			// 并且，滚动距离已经超过了头部的高度 (避免刚开始滚动一点点就隐藏)
			// 设置 isScrolled 为 true，这将给 .Index-header 添加 'fixed-header' 类
			isScrolled.value = true;

		} else if (currentScrollTop < lastScrollTop.value) {
			// --- 向上滚动 ---
			// 当前滚动位置 < 上次位置，表示向上滚动
			// 设置 isScrolled 为 false，这将移除 'fixed-header' 类
			isScrolled.value = false;
		}
		// else {
		// 如果 currentScrollTop === lastScrollTop.value (例如水平滚动或无垂直滚动)，则不改变状态
		// 如果 currentScrollTop <= headerHeight 并且向下滚动，也不隐藏，保持显示
		// }

		// 更新上一次滚动的位置，为下一次事件触发时的比较做准备
		// 使用 Math.max 确保 lastScrollTop 的值不会小于 0 (虽然 scrollTop 通常不会为负)
		lastScrollTop.value = Math.max(0, currentScrollTop);
	};


	function addPeople() {
		const res = axios.get("/api/people/update");
	}

	const notice = ref([]);
	const isshownotice = ref(false); // 默认设为 false，避免闪烁

	function addNotice() {
		const res = axios.get("/api/notice/selectAll");
		res
			.then(response => {
				if (response.data.code == 200) {
					const da = response.data.data;
					const currentTime = Date.now();

					// 遍历数据数组
					da.forEach(item => {
						if (item.time > currentTime) {
							// 如果时间未过期，则添加到 novicedata 数组
							notice.value.push(item);
						}
					});
					// 只在第一次访问且有公告时显示
					if (!localStorage.getItem('hasVisitedNotice') && notice.value.length > 0) {
						isshownotice.value = true;
						localStorage.setItem('hasVisitedNotice', 'true');
					}
					console.log(notice.value);
				} else {
					console.log('获取公告失败:', response.data.message);
				}
			})
			.catch(error => {
				// 请求失败，处理错误
				if (error.response) {
					// 请求已发送，但服务器响应的状态码不在 2xx 范围内
					console.log('响应状态码:', error.response.status);
					console.log('响应数据:', error.response.data);
				} else if (error.request) {
					// 请求已发送，但没有收到响应
					console.log('没有收到响应:', error.request);
				} else {
					// 在设置请求时发生错误
					console.log('错误信息:', error.message);
				}
			});
	}
	
	function changeisshow(){
		isshownotice.value = false;
	}

	// 检查是否是首次访问
	const checkFirstVisit = () => {
		const hasVisited = localStorage.getItem('hasVisited');
		if (!hasVisited) {
			isLoading.value = true;
			localStorage.setItem('hasVisited', 'true');
		}
	};

	// --- 生命周期钩子 ---

	// 组件挂载后执行
	onMounted(() => {
		// 检查是否是首次访问
		checkFirstVisit();
		
		// 只有在首次访问时才执行加载动画
		if (isLoading.value) {
			// 启动加载进度条
			simulateLoading();
			
			// 加载数据并初始化页面
			Promise.all([
				// 预加载主要资源
				new Promise(resolve => {
					addPeople();
					addNotice();
					resolve();
				}),
				// 预加载图片
				...backgroundurl.map(url => 
					new Promise(resolve => {
						const img = new Image();
						img.src = url;
						img.onload = resolve;
						img.onerror = resolve; // 即使加载失败也继续
					})
				),
				// 给页面至少2秒的加载时间，让用户能够看到进度条动画
				new Promise(resolve => setTimeout(resolve, 2000))
			]).then(() => {
				// 所有资源加载完成
				completeLoading();
			});
		} else {
			// 非首次访问，直接初始化页面
			addPeople();
			addNotice();
		}
		
		if (ppt.value) {
			// Set the very first background image immediately (without effect)
			const initialImageUrl = backgroundurl[currentIndex.value];
			ppt.value.style.backgroundImage = `url('${initialImageUrl}')`;
			// Prepare index for the first interval change
			currentIndex.value = (currentIndex.value + 1) % backgroundurl.length;
		} else {
			console.error("PPT element not found on mount");
		}

		// --- Start Interval Timer ---
		// Change background every 8 seconds (will call changeBackground)
		intervalId.value = setInterval(changeBackground, 8000); // 8000ms = 8 seconds

		// 向 window 对象添加 'scroll' 事件监听器，并指定 handleScroll 函数作为回调
		window.addEventListener('scroll', handleScroll);
	});

	// 组件卸载前执行
	onUnmounted(() => {
		// 从 window 对象移除之前添加的 'scroll' 事件监听器
		// 传入相同的 handleScroll 函数引用以确保正确移除
		// 这是非常重要的，可以防止内存泄漏
		window.removeEventListener('scroll', handleScroll);
		if (intervalId.value) {
			clearInterval(intervalId.value);
		}
		// Clear any pending timeout for adding the class effect
		if (showClassTimeoutId.value) {
			clearTimeout(showClassTimeoutId.value);
		}
		// 清除进度条计时器
		if (progressInterval) {
			clearInterval(progressInterval);
		}
		// 清除光标闪烁计时器
		if (cursorInterval) {
			clearInterval(cursorInterval);
		}
	});
</script>

<style lang="scss" scoped>
	* {
		margin: 0px;
		padding: 0px;
		border: none;
		border-radius: 0px;
		font-size: 14px;
		font-weight: 300px;
		color: #000;
	}

	/* 加载页面样式 - 科技风命令行风格 */
	.loading-screen {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: #081426;
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 9999;
		overflow: hidden;
	}
	
	/* 科技风网格背景 */
	.cyber-grid {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-image: 
			linear-gradient(rgba(0, 40, 70, 0.8) 1px, transparent 1px),
			linear-gradient(90deg, rgba(0, 40, 70, 0.8) 1px, transparent 1px);
		background-size: 20px 20px;
		opacity: 0.2;
		z-index: 1;
	}
	
	/* 流动的矩阵线 */
	.cyber-lines {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		overflow: hidden;
		z-index: 1;
		
		&::before {
			content: "";
			position: absolute;
			width: 200%;
			height: 200%;
			top: -50%;
			left: -50%;
			background-image: linear-gradient(0deg, rgba(0, 100, 200, 0.1) 25%, transparent 25%, transparent 50%, rgba(0, 100, 200, 0.1) 50%, rgba(0, 100, 200, 0.1) 75%, transparent 75%, transparent);
			background-size: 40px 40px;
			animation: cyber-lines-animation 10s linear infinite;
			opacity: 0.3;
		}
	}
	
	@keyframes cyber-lines-animation {
		0% {
			transform: rotate(0deg);
		}
		100% {
			transform: rotate(360deg);
		}
	}
	
	/* 悬浮粒子效果 */
	.cyber-particles {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 1;
		overflow: hidden;
		
		&::before {
			content: "";
			position: absolute;
			width: 100%;
			height: 100%;
			background-image: radial-gradient(rgba(0, 150, 220, 0.3) 1px, transparent 1px),
							  radial-gradient(rgba(0, 220, 250, 0.2) 1px, transparent 1px);
			background-size: 30px 30px, 50px 50px;
			background-position: 0 0, 15px 15px;
			animation: cyber-particles-animation 8s linear infinite;
		}
	}
	
	@keyframes cyber-particles-animation {
		0% {
			transform: translateY(0);
		}
		100% {
			transform: translateY(100px);
		}
	}

	.loading-container {
		width: 90%;
		max-width: 600px;
		display: flex;
		flex-direction: column;
		align-items: center;
		position: relative;
		z-index: 2;
	}

	.loading-logo {
		font-size: 32px;
		font-weight: bold;
		margin-bottom: 30px;
		color: #0cf;
		text-align: center;
		letter-spacing: 2px;
		text-shadow: 0 0 10px rgba(0, 200, 255, 0.7),
					 0 0 20px rgba(0, 200, 255, 0.5),
					 0 0 30px rgba(0, 200, 255, 0.3);
		animation: text-glow 2s ease-in-out infinite alternate;
	}
	
	@keyframes text-glow {
		0% {
			text-shadow: 0 0 10px rgba(0, 200, 255, 0.7),
						 0 0 20px rgba(0, 200, 255, 0.5),
						 0 0 30px rgba(0, 200, 255, 0.3);
		}
		100% {
			text-shadow: 0 0 15px rgba(0, 200, 255, 0.9),
						 0 0 25px rgba(0, 200, 255, 0.7),
						 0 0 35px rgba(0, 200, 255, 0.5);
		}
	}
	
	/* 命令行终端样式 */
	.loading-terminal {
		width: 100%;
		background-color: rgba(0, 20, 40, 0.9);
		border-radius: 6px;
		box-shadow: 0 0 20px rgba(0, 150, 220, 0.5),
					inset 0 0 15px rgba(0, 0, 0, 0.8);
		border: 1px solid rgba(0, 150, 220, 0.3);
		overflow: hidden;
	}
	
	.terminal-header {
		height: 30px;
		background-color: rgba(10, 30, 50, 0.8);
		display: flex;
		align-items: center;
		padding: 0 10px;
		border-bottom: 1px solid rgba(0, 150, 220, 0.3);
	}
	
	.terminal-button {
		width: 12px;
		height: 12px;
		border-radius: 50%;
		margin-right: 6px;
		background-color: rgba(255, 70, 70, 0.8);
		
		&:nth-child(2) {
			background-color: rgba(255, 180, 60, 0.8);
		}
		
		&:nth-child(3) {
			background-color: rgba(50, 190, 80, 0.8);
		}
	}
	
	.terminal-title {
		margin-left: auto;
		margin-right: auto;
		color: #aaa;
		font-size: 12px;
		font-family: monospace;
	}
	
	.terminal-body {
		padding: 15px;
		font-family: 'Courier New', monospace;
	}
	
	.terminal-line {
		margin: 8px 0;
		color: #0c0;
		font-size: 14px;
		line-height: 1.4;
		font-family: 'Courier New', monospace;
	}
	
	.prompt {
		color: #0cf;
		margin-right: 8px;
	}
	
	.command {
		color: #fff;
	}
	
	.progress-line {
		display: flex;
		align-items: center;
		margin-top: 15px;
		margin-bottom: 15px;
		white-space: nowrap;
	}
	
	.progress-text {
		color: #0cf;
		font-weight: bold;
	}
	
	.progress-container {
		display: inline-block;
		width: 520px;
		overflow: hidden;
		white-space: nowrap;
		letter-spacing: 0px;
		font-family: monospace;
		font-size: 14px;
	}
	
	.progress-bar {
		color: #0f0;
	}
	
	.cursor {
		color: #0f0;
		animation: blink 1s step-end infinite;
	}
	
	@keyframes blink {
		0%, 100% { opacity: 1; }
		50% { opacity: 0; }
	}
	
	.progress-percentage {
		margin-left: 10px;
		color: #fff;
		font-weight: bold;
	}
	
	.success-text {
		color: #0f0;
		font-weight: bold;
	}

	.Index-header {
		width: 100%;
		height: 50px;
		// background-color: antiquewhite;
		position: fixed;
		/* 改为 fixed 或 sticky 以便在滚动时保持在顶部 */
		top: 0;
		left: 0;
		z-index: 10;
		transition: transform 0.3s ease;
		/* 改为使用 transform 过渡，性能更好 */
		transform: translateY(0);
		/* 初始状态 */
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		/* 可选：添加阴影 */
	}

	.fixed-header {
		/* margin-top: -50px;  <-- 使用 transform 替代 margin-top */
		transform: translateY(-100%);
		/* 向上移动自身高度 */
	}

	.Index-body {
		width: 100%;
		height: 1500px;
		margin-top: -50px;
		// background-color: aquamarine;

		.Index-ppt {
			width: 100%;
			height: 957px;
			background-size: 100% 100%;
			/* background-size: cover; */
			background-attachment: fixed;
			background-position: center;
			position: relative;
			overflow: hidden;
			/* left: -100px; */
			transform: scale(1);

			/* transition: background-size 5s ease-in-out, left 5s ease-in-out; */
			.Ware {
				position: relative;
				top: 657px;
				z-index: 2;
				overflow: hidden;
			}
		}

		.Index-show {
			background-size: 120% 120%;
			/* transform: scale(1.2); */
			transform-origin: center center;
			transition: background-size 5s ease-in-out, left 5s ease-in-out;
		}
	}

	.notice {
		position: absolute;
		width: 600px;
		height: 600px;
		background-color: #e0e0e0;
		border-radius: 20px;
		top: 100px;
		left: 33%;
		display: flex;
		align-items: center;
		justify-content: center;

		.notice-box {
			width: 80%;
			height: 400px;
			display: block;
			// align-items: center;
			// justify-content: center;
			background-color: antiquewhite;
			border-radius: 10px;
			overflow: auto;

			&::-webkit-scrollbar {
				display: none;
			}


			.notice-txt {
				width: 100%;
				// height: 200px;
				display: flex;
				justify-content: center;
				align-items: center;
				margin: 20px 0px 0px 0px;
				font-size: 18px;
				word-wrap: break-word;
				word-break: break-all;
			}
		}

		h1 {
			position: absolute;
			font-size: 40px;
			font-weight: 500;
			top: 30px;
		}

		button {
			position: absolute;
			top: 520px;
			width: 200px;
			height: 50px;
			cursor: pointer;
		}
	}
</style>